package servlet;

import dao.UserDAO;
import dao.UserDAOImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import model.User;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/users")
public class UserServlet extends HttpServlet {
    private UserDAO userDAO;

    @Override
    public void init() {
        userDAO = new UserDAOImpl(); // 初始化DAO
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-ijt");

        String action = request.getParameter("action");

        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            if ("login".equals(action)) {
                loginUesr(request, out);
            } else if ("insert".equals(action)) {
                insertUser(request, out);
            } else if ("update".equals(action)) {
                updateUser(request, out);
            } else {
                out.print("{\"success\": false, \"message\": \"未知操作\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"服务器内部错误\"}");
        } finally {
            out.flush();
        }
    }

    // 处理登录逻辑
    private void loginUesr(HttpServletRequest request, PrintWriter out) {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        User user = userDAO.findByAccountAndPassword(account, password);

        if (user != null) {
            // 登录成功，返回成功响应
            out.print("{\"success\": true}");
        } else {
            // 登录失败，返回失败响应
            out.print("{\"success\": false, \"message\": \"账号或密码错误\"}");
        }
    }

    // 处理注册逻辑
    private void insertUser(HttpServletRequest request, PrintWriter out) {
        String account = request.getParameter("account");
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String sex = request.getParameter("sex");
        String introduction = request.getParameter("introduction");

        // 打印日志
        System.out.println("Received insert request: account=" + account + ", userName=" + userName + ", userPwd=" + userPwd + ", sex=" + sex + ", introduction=" + introduction);

        User newUser = new User();
        newUser.setAccount(account);
        newUser.setUserName(userName);
        newUser.setUserPwd(userPwd);
        newUser.setSex(sex);
        newUser.setIntroduction(introduction);

        int result = userDAO.insert(newUser);
        if (result > 0) {
            out.print("{\"success\": true, \"message\": \"用户注册成功\"}");
        } else {
            out.print("{\"success\": false, \"message\": \"用户注册失败\"}");
        }
    }

    // 处理更新逻辑
    private void updateUser(HttpServletRequest request, PrintWriter out) {
        int userId = Integer.parseInt(request.getParameter("id"));
        String account = request.getParameter("account");
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String sex = request.getParameter("sex");
        String introduction = request.getParameter("introduction");

        User newUser = new User();
        newUser.setUserId(userId);
        newUser.setAccount(account);
        newUser.setUserName(userName);
        newUser.setUserPwd(userPwd);
        newUser.setSex(sex);
        newUser.setIntroduction(introduction);

        int result = userDAO.update(newUser);
        if (result > 0) {
            out.print("{\"success\": true, \"message\": \"用户更新成功\"}");
        } else {
            out.print("{\"success\": false, \"message\": \"用户更新失败\"}");
        }
    }
}